// UserController.java
package com.tzkyzj.tiremanager.contorller;

import com.tzkyzj.tiremanager.entity.User;
import com.tzkyzj.tiremanager.entity.User.UserRole; // 添加这个导入
import com.tzkyzj.tiremanager.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    // 获取所有用户列表
    @GetMapping
    public ResponseEntity<?> getAllUsers(HttpServletRequest request) {
        System.out.println("=== 开始权限检查 ===");

        // 检查权限 - 只有管理员可以访问
        HttpSession session = request.getSession(false);
        if (session == null) {
            System.out.println("Session 不存在，返回 401");
            return ResponseEntity.status(401).body(createErrorResponse("未登录"));
        }

        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            System.out.println("Session 中无用户信息，返回 401");
            return ResponseEntity.status(401).body(createErrorResponse("用户信息不存在"));
        }

        System.out.println("当前用户: " + currentUser.getUsername() + ", 角色: " + currentUser.getRole());

        // 修复：使用枚举比较而不是字符串比较
        UserRole userRole = currentUser.getRole();
        System.out.println("用户角色枚举: " + userRole);
        System.out.println("比较 UserRole.ADMIN: " + (userRole == UserRole.ADMIN));

        if (userRole != UserRole.ADMIN) {
            System.out.println("用户角色不是 ADMIN，返回 403");
            return ResponseEntity.status(403).body(createErrorResponse("权限不足，需要管理员权限。当前角色: " + userRole));
        }

        System.out.println("权限检查通过，获取用户列表");
        List<User> users = userService.getAllUsers();
        return ResponseEntity.ok(users);
    }

    // 创建新用户
    @PostMapping
    public ResponseEntity<?> createUser(@RequestBody User user, HttpServletRequest request) {
        System.out.println("=== 创建用户权限检查 ===");

        // 检查权限
        HttpSession session = request.getSession(false);
        if (session == null) {
            System.out.println("创建用户: Session 不存在，返回 401");
            return ResponseEntity.status(401).body(createErrorResponse("未登录"));
        }

        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            System.out.println("创建用户: Session 中无用户信息，返回 401");
            return ResponseEntity.status(401).body(createErrorResponse("用户信息不存在"));
        }

        System.out.println("创建用户: 当前用户: " + currentUser.getUsername() + ", 角色: " + currentUser.getRole());

        UserRole userRole = currentUser.getRole();
        if (userRole != UserRole.ADMIN) {
            System.out.println("创建用户: 用户角色不是 ADMIN，返回 403");
            return ResponseEntity.status(403).body(createErrorResponse("权限不足，需要管理员权限。当前角色: " + userRole));
        }

        System.out.println("创建用户: 权限检查通过，开始创建用户");

        try {
            User createdUser = userService.createUser(user);
            System.out.println("创建用户成功: " + createdUser.getUsername());
            return ResponseEntity.ok(createdUser);
        } catch (Exception e) {
            System.out.println("创建用户异常: " + e.getMessage());
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    // 更新用户状态
    @PutMapping("/{userId}")
    public ResponseEntity<?> updateUserStatus(@PathVariable Long userId,
                                              @RequestBody Map<String, Boolean> requestBody,
                                              HttpServletRequest request) {
        System.out.println("=== 更新用户状态权限检查 ===");

        // 检查权限
        HttpSession session = request.getSession(false);
        if (session == null) {
            System.out.println("更新用户状态: Session 不存在，返回 401");
            return ResponseEntity.status(401).body(createErrorResponse("未登录"));
        }

        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            System.out.println("更新用户状态: Session 中无用户信息，返回 401");
            return ResponseEntity.status(401).body(createErrorResponse("用户信息不存在"));
        }

        System.out.println("更新用户状态: 当前用户: " + currentUser.getUsername() + ", 角色: " + currentUser.getRole());

        UserRole userRole = currentUser.getRole();
        if (userRole != UserRole.ADMIN) {
            System.out.println("更新用户状态: 用户角色不是 ADMIN，返回 403");
            return ResponseEntity.status(403).body(createErrorResponse("权限不足，需要管理员权限。当前角色: " + userRole));
        }

        Boolean enabled = requestBody.get("enabled");
        if (enabled == null) {
            return ResponseEntity.badRequest().body(createErrorResponse("enabled字段是必需的"));
        }

        try {
            userService.updateUserStatus(userId, enabled);
            System.out.println("更新用户状态成功: " + userId);
            return ResponseEntity.ok(createSuccessResponse("用户状态更新成功"));
        } catch (Exception e) {
            System.out.println("更新用户状态异常: " + e.getMessage());
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    // 删除用户
    @DeleteMapping("/{userId}")
    public ResponseEntity<?> deleteUser(@PathVariable Long userId, HttpServletRequest request) {
        System.out.println("=== 删除用户权限检查 ===");

        // 检查权限
        HttpSession session = request.getSession(false);
        if (session == null) {
            System.out.println("删除用户: Session 不存在，返回 401");
            return ResponseEntity.status(401).body(createErrorResponse("未登录"));
        }

        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            System.out.println("删除用户: Session 中无用户信息，返回 401");
            return ResponseEntity.status(401).body(createErrorResponse("用户信息不存在"));
        }

        System.out.println("删除用户: 当前用户: " + currentUser.getUsername() + ", 角色: " + currentUser.getRole());

        UserRole userRole = currentUser.getRole();
        if (userRole != UserRole.ADMIN) {
            System.out.println("删除用户: 用户角色不是 ADMIN，返回 403");
            return ResponseEntity.status(403).body(createErrorResponse("权限不足，需要管理员权限。当前角色: " + userRole));
        }

        try {
            userService.deleteUser(userId);
            System.out.println("删除用户成功: " + userId);
            return ResponseEntity.ok(createSuccessResponse("用户删除成功"));
        } catch (Exception e) {
            System.out.println("删除用户异常: " + e.getMessage());
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    // 权限检查辅助方法
    private boolean hasAdminPermission(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return false;
        }

        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            return false;
        }

        UserRole userRole = currentUser.getRole();
        boolean hasPermission = userRole == UserRole.ADMIN;

        System.out.println("hasAdminPermission 检查: 用户=" + currentUser.getUsername() +
                ", 角色=" + userRole + ", 结果=" + hasPermission);

        return hasPermission;
    }

    private Map<String, String> createErrorResponse(String message) {
        Map<String, String> response = new HashMap<>();
        response.put("message", message);
        return response;
    }

    private Map<String, String> createSuccessResponse(String message) {
        Map<String, String> response = new HashMap<>();
        response.put("message", message);
        return response;
    }

    // 添加一个调试端点，用于检查当前会话状态
    @GetMapping("/debug")
    public ResponseEntity<Map<String, Object>> debugSession(HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();

        HttpSession session = request.getSession(false);
        if (session != null) {
            response.put("sessionExists", true);
            response.put("sessionId", session.getId());
            response.put("sessionCreationTime", session.getCreationTime());
            response.put("lastAccessedTime", session.getLastAccessedTime());

            User currentUser = (User) session.getAttribute("currentUser");
            if (currentUser != null) {
                Map<String, Object> userInfo = new HashMap<>();
                userInfo.put("id", currentUser.getId());
                userInfo.put("username", currentUser.getUsername());
                userInfo.put("role", currentUser.getRole());
                userInfo.put("roleType", currentUser.getRole() != null ? currentUser.getRole().getClass().getName() : "null");
                userInfo.put("roleStringValue", currentUser.getRole() != null ? currentUser.getRole().name() : "null");
                userInfo.put("enabled", currentUser.getEnabled());
                response.put("currentUser", userInfo);
            } else {
                response.put("currentUser", "null");
            }
        } else {
            response.put("sessionExists", false);
        }

        return ResponseEntity.ok(response);
    }
}